var mongoose = require('mongoose');
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID; // mogodb的ObjectId对象 查询数据使用
var lookupData = require('../module/lookupData'); // 查询数据
var upload = require('../module/uploadFile');  // 图片上传配置
var insertData = require('../module/insertData'); // 插入数据
var pagingData = require('../module/pagingData'); // 分页代码


// 数据库地址
var url = 'mongodb://localhost:27017';

// Database Name数据库名称
var dbName = 'config';
var db;

MongoClient.connect(url, function(err, client) {
    if (err) throw err;
    console.log('数据库链接成功.....');
    db = client.db(dbName);
});

// 解决跨域 https://www.cnblogs.com/king-ying/p/7248816.html
module.exports = function(app) {
    app.all("*", function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
        res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
        res.header("X-Powered-By", ' 3.2.1')
        if (req.method == "OPTIONS") res.send(200);/*让options请求快速返回*/
        else next();
    });

    app.get('/swiper', function(req, res) { // 首页轮播图
        if (db) {
            lookupData({}, db, 'swiper', function(data) {
                res.send(data[0]);
            });
        }
    });

    app.post('/upload/star', upload.single('logo'), function(req, res) { // 上传图片及明星基本信息 
        var result = req.body;
        var uploadObj = [{
            logo: req.file.filename,
            name: result.name,
            hobby: result.hobby,
            address: result.address,
            livesong: result.livesong,
            detailed: result.detailed,
        }]
        if (db) {
            insertData(db, 'personalInfo', uploadObj, function(data) {
                res.send('完成');
            })
        }
    });

    // 获取明星列表
    app.get('/upload/starList', function(req, res) {
        if (db) {
            lookupData({}, db, 'personalInfo', function(data) {
                res.send(data)
            });
        }
    })

    // 获取单个明星详细信息
    app.get('/single/starInfor', function(req, res) {
        if (db) {
            lookupData({ _id: ObjectID(req.query['_id']) }, db, 'personalInfo', function(data) {
                res.send(data[0])
            })
        }
    })

    app.post('/index/pagelist', function(req, res) { // 实现分页查询
        var page = req.body.page;
        var rows = req.body.rows;
        if (db) {
            pagingData(page, rows, db, 'personalInfo', res);
        }
    })
}